import React, {cloneElement, FC, isValidElement, ReactNode, useEffect, useState} from "react";
import {
    CircularProgress,
    Drawer,
    IconButton,
    ListItemIcon,
    ListItemText,
    Menu,
    MenuItem, Tooltip,
    useTheme
} from "@mui/material";
import DGActionBar from "./DGActionBar/DGActionBar.tsx";
import {AccountCircle, ArrowBack, Logout, Settings} from "@mui/icons-material";
import {useNavigate} from "react-router-dom";
import PaidSharpIcon from "@mui/icons-material/PaidSharp";
import ManageHistorySharpIcon from "@mui/icons-material/ManageHistorySharp";
import DGToast from "./DGToast.tsx";
import {AlertColor} from "@mui/material/Alert/Alert";
import DGConnect from "../sources/DGConnect.ts";
import {Util} from "../sources/Util.ts";
import AppProvider from "../sources/AppProvider.ts";
import DGAvatar from "./DGAvatar.tsx";

import DGLoginIndex from "../framework/DGAccountOperates/Login/DGLoginIndex.tsx";
import DGLoginPassword from "../framework/DGAccountOperates/Login/DGLoginPassword.tsx";
import DGLoginMore from "../framework/DGAccountOperates/Login/DGLoginMore.tsx";

import DGForgetIndex from "../framework/DGAccountOperates/Forget/DGForgetIndex.tsx";
import DGForgetCode from "../framework/DGAccountOperates/Forget/DGForgetCode.tsx";
import DGForgetNewPwd from "../framework/DGAccountOperates/Forget/DGForgetNewPwd.tsx";
import DGForgetResult from "../framework/DGAccountOperates/Forget/DGForgetResult.tsx";

import DGRegIndex from "../framework/DGAccountOperates/Register/DGRegIndex.tsx";
import DGRegEmail from "../framework/DGAccountOperates/Register/DGRegEmail.tsx";
import DGRegCode from "../framework/DGAccountOperates/Register/DGRegCode.tsx";
import DGRegAccount from "../framework/DGAccountOperates/Register/DGRegAccount.tsx";
import DGRegPassword from "../framework/DGAccountOperates/Register/DGRegPassword.tsx";
import DGRegName from "../framework/DGAccountOperates/Register/DGRegName.tsx";
import DGRegResult from "../framework/DGAccountOperates/Register/DGRegResult.tsx";
import DGLoginCode from "../framework/DGAccountOperates/Login/DGLoginCode.tsx";

// Props 接口
interface DGDrawerActionProps {
    children: ReactNode,
    icon: ReactNode,
    title: string | undefined
}

interface DGToastProps {
    state: boolean,
    severity: AlertColor,
    text: string
}

const DGDrawerAction: FC<DGDrawerActionProps> = ({children, icon, title}) => {
    // 查询主题
    const m = useTheme().palette.mode === "light";
    // 主题上下文
    const TC = AppProvider.useAppThemeContext();
    // 全局上下文
    const App = AppProvider.useAppContext();
    // 路由操作
    const router = useNavigate();
    // Toast 弹窗
    const [toast, setToast] = useState<DGToastProps>({state: false, severity: "info", text: ""});
    // 侧滑面板---开关状态
    const [MenuState, setMenuState] = useState(false);
    // 菜单面板---开关状态
    const [MenuElement, setMenuElement] = useState<HTMLElement | null>(null);
    // 菜单面板---退出登陆状态
    const [ExitState, setExitState] = useState(false);
    // 登录面板---展示弹窗 DV = DialogView
    const [view, setView] = useState("");

    // —————————————————————————————————————————————————————————————————————————————————————————————————————————————————

    // 关闭所有面板函数
    const handleClose = (id: number) => {
        // 关闭侧滑面板
        setMenuState(false);
        // 关闭菜单面板
        setMenuElement(null);
        // 关闭登陆面板
        setView("");
        // 将记录从历史堆栈中退回
        if (id === 1 && !ExitState) router(-1);
    }

    // —————————————————————————————————————————————————————————————————————————————————————————————————————————————————

    // 侧滑面板---打开面板
    const handleOpen = () => {
        setMenuState(!MenuState);
        // 将记录推入历史堆栈
        router("?drawer");
    }

    // 侧滑面板---设置按钮
    const handleOpenSettings = () => {
        // 从记录堆栈后退
        handleClose(1);
        // 跳转设置页面
        setTimeout(() => router("settings", {replace: true}), 1);
    }

    // 侧滑面板---菜单列表组件
    const children_props = {close: () => handleClose(1)};

    // —————————————————————————————————————————————————————————————————————————————————————————————————————————————————

    // 菜单面板---切换页面
    const handleSwitchView = (text: string, re: boolean) => {
        // 关闭所有面板
        handleClose(1);
        // 延迟执行切换
        setTimeout(() => router(text, {replace: re}), 5);
    }

    // 菜单面板---退出登陆函数
    const handleExitLogin = () => {
        // 开始退出加载
        setExitState(true);
        // 发起退出登录请求
        DGConnect.POST(JSON.stringify({type: "login", exit: 1}), result => {
            // 关闭退出加载
            setExitState(false);
            // 返回错误信息
            if (result.data.code !== 200) return setToast({
                state: true, severity: "error", text: result.data.message
            });
            // 清除本地登陆信息（退出登录）
            App!.setUserInfo(null);
            // 刷新主题
            const ThemeMode = parseInt(Util.Storage.getLocal("THEME-MODE"), 10);
            TC!.setThemeMode(ThemeMode !== 0, ThemeMode);
            // 返回成功信息
            setToast({state: true, severity: "success", text: "已退出登录！"});
            // 关闭面板
            handleClose(1);
        }, error => {
            // 关闭退出加载
            setExitState(false);
            // 返回错误信息
            setToast({state: true, severity: "error", text: "退出登录失败！" + error['stack']});
        });
    }

    // —————————————————————————————————————————————————————————————————————————————————————————————————————————————————

    // 登录面板---切换弹窗 hSDV = handleSwitchDialogView
    const hSDV = (text: string) => {
        // 切换弹窗
        setView(text);
        // 替换路由
        router("?" + text, {replace: true});
    }

    // 登录面板---点击账户图标按钮函数
    const handleAccountMenu = (event: React.MouseEvent<HTMLElement>) => {
        // 未登录进行登陆弹窗
        if (App && App.info) {
            // 推入历史堆栈
            router("?menu");
            // 已登陆展示弹窗
            setMenuElement(event.currentTarget);
        } else {
            // 推入历史堆栈
            router("?");
            hSDV("login_index");
        }
    }

    // —————————————————————————————————————————————————————————————————————————————————————————————————————————————————

    // 加载返回和后退识别
    useEffect(() => {
        const handlePopState = () => handleClose(0);
        window.addEventListener('popstate', handlePopState);
        return () => window.removeEventListener('popstate', handlePopState);
    }, [MenuState]);

    // —————————————————————————————————————————————————————————————————————————————————————————————————————————————————

    return (<>
        {/* Toast 组件 */}
        <DGToast state={toast} close={() => setToast({state: false, severity: toast.severity, text: toast.text})}/>

        {/* 侧滑栏 */}
        <Drawer open={MenuState} onClose={() => handleClose(1)} PaperProps={{sx: {width: "80%", height: "100%"}}}>
            {/* 侧滑栏顶部导航栏 */}
            <DGActionBar icon={<ArrowBack/>} title="返回" click={() => handleClose(1)}>
                <IconButton color="inherit" onClick={handleOpenSettings}><Settings/></IconButton>
            </DGActionBar>
            {/* 侧滑栏子组件 */}
            {isValidElement(children) && cloneElement(children, children_props)}
        </Drawer>


        {/* 主页面导航栏 */}
        <DGActionBar icon={icon} title={title} click={handleOpen}>
            <Tooltip title="账户信息">
                <IconButton color="inherit" id="user" aria-label="user" onClick={handleAccountMenu}>
                    <DGAvatar
                        src=" " rounded small bgWhite={!m} bgGrey={m}
                        alt={App!.info ? String(App!.info['name']) : ""}/>
                </IconButton>
            </Tooltip>
        </DGActionBar>

        {/* 已登陆菜单 */}
        <Menu
            anchorEl={MenuElement}
            open={Boolean(MenuElement)}
            onClose={() => handleClose(1)}
            transformOrigin={{horizontal: 'right', vertical: 'top'}}
            anchorOrigin={{horizontal: 'right', vertical: 'bottom'}}
            MenuListProps={{style: {padding: 0,}}}
            PaperProps={{
                elevation: 0, sx: {
                    overflow: 'visible', filter: 'drop-shadow(0px 2px 8px rgba(0,0,0,0.32))', mt: 2.5, '&::before': {
                        content: '""',
                        display: 'block',
                        position: 'absolute',
                        top: 0,
                        right: 14,
                        width: 10,
                        height: 10,
                        backgroundColor: 'background.paper',
                        transform: 'translateY(-50%) rotate(45deg)',
                        zIndex: 0,
                    },
                },
            }}>
            {/* 我的账户菜单按钮 */}
            <MenuItem disabled={ExitState} onClick={() => handleSwitchView("account", true)}>
                <ListItemIcon><AccountCircle/></ListItemIcon>
                <ListItemText primary="我的账户"/>
            </MenuItem>
            {/* 我的钱包菜单按钮 */}
            <MenuItem disabled={ExitState} onClick={() => handleSwitchView("money", true)}>
                <ListItemIcon><PaidSharpIcon/></ListItemIcon>
                <ListItemText primary="我的钱包"/>
            </MenuItem>
            {/* 操作记录菜单按钮 */}
            <MenuItem disabled={ExitState} onClick={() => handleSwitchView("security/options", false)}>
                <ListItemIcon><ManageHistorySharpIcon/></ListItemIcon>
                <ListItemText primary="操作记录"/>
            </MenuItem>
            {/* 退出登陆菜单按钮 */}
            <MenuItem disabled={ExitState} onClick={handleExitLogin}>
                <ListItemIcon>{ExitState ? <CircularProgress size={20}/> : <Logout/>}</ListItemIcon>
                <ListItemText primary="退出登陆"/>
            </MenuItem>
        </Menu>


        {/* 登录弹窗 */}
        <DGLoginIndex state={(view === "login_index")} switchView={(text: string) => hSDV(text)}/>
        {/* 登录验证码 */}
        <DGLoginCode state={(view === "login_code")} switchView={(text: string) => hSDV(text)}/>
        {/* 登录密码弹窗 */}
        <DGLoginPassword state={view === "login_password"} switchView={(text: string) => hSDV(text)}/>
        {/* 登录更多弹窗 */}
        <DGLoginMore state={view === "login_more"} switchView={(text: string) => hSDV(text)}/>


        {/* 忘记密码 */}
        <DGForgetIndex state={view === "forget_index"} switchView={(text: string) => hSDV(text)} left/>
        {/* 忘记密码获取验证码弹窗 */}
        <DGForgetCode state={view === "forget_code"} switchView={(text: string) => hSDV(text)} left/>
        {/* 设置新密码弹窗 */}
        <DGForgetNewPwd state={view === "forget_new"} switchView={(text: string) => hSDV(text)}/>
        {/* 密码重置结果 */}
        <DGForgetResult state={view === "forget_result"} switchView={(text: string) => hSDV(text)}/>


        {/* 注册账号组件 */}
        <DGRegIndex state={view === "reg_index"} switchView={(text: string) => hSDV(text)}/>
        {/* 设置注册邮箱 */}
        <DGRegEmail state={view === "reg_email"} switchView={(text: string) => hSDV(text)}/>
        {/* 核对验证码 */}
        <DGRegCode state={view === "reg_code"} switchView={(text: string) => hSDV(text)}/>
        {/* 设置注册账户 */}
        <DGRegAccount state={view === "reg_account"} switchView={(text: string) => hSDV(text)}/>
        {/* 设置密码 */}
        <DGRegPassword state={view === "reg_password"} switchView={(text: string) => hSDV(text)}/>
        {/* 设置昵称 */}
        <DGRegName state={view === "reg_name"} switchView={(text: string) => hSDV(text)}/>
        {/* 注册结果 */}
        <DGRegResult state={view === "reg_result"} switchView={(text: string) => hSDV(text)}/>

    </>);
}

export default DGDrawerAction;
